// 威胁情报中心-情报源管理脚本

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
  // 初始化应用
  initApp();
});

// 应用初始化函数
function initApp() {
  // 初始化本地存储数据
  initializeData();
  
  // 渲染情报源列表
  renderIntelligenceSources();
  
  // 初始化质量分布图表
  initQualityChart();
  
  // 绑定导航事件
  bindNavigationEvents();
  
  // 初始化交互功能
  initInteractions();
  
  // 初始化通知系统
  initNotifications();
  
  // 初始化用户体验增强功能
  initUXEnhancements();
  
  // 初始化添加专题模态框
  initAddTopicModal();
  
  // 初始化编辑模态框事件
  initEditModalEvents();
}

// 初始化本地存储数据
function initializeData() {
  // 数据管理器已经在创建时初始化了默认数据
  // 这里只需确保数据可以正常访问
  try {
    const sources = dataManager.getIntelligenceSources();
    console.log('本地存储数据初始化完成，共有', sources.length, '个情报源');
  } catch (error) {
    console.error('数据初始化错误:', error);
    // 重置数据管理器
    dataManager = new DataManager();
  }
}

// 渲染情报源列表
function renderIntelligenceSources() {
  // 从DataManager获取情报源数据
  const sources = dataManager.getIntelligenceSources();
  const container = document.getElementById('intelligence-sources');
  
  if (!container) return;
  
  // 确保保持网格布局样式
  container.className = 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4';
  
  // 清空容器
  container.innerHTML = '';
  
  // 绑定右侧面板的导出按钮事件
  const exportBtn = document.getElementById('export-data-btn');
  if (exportBtn) {
    exportBtn.addEventListener('click', showExportOptions);
  }
  
  if (sources.length === 0) {
    // 如果没有数据，显示空状态
    container.innerHTML = `
      <div class="text-center py-12 w-full">
        <i class="fa fa-database text-gray-300 text-4xl mb-4"></i>
        <p class="text-gray-500">暂无情报源数据</p>
        <button id="add-first-source" class="mt-4 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
          添加第一个情报源
        </button>
      </div>
    `;
    
    // 绑定添加按钮事件
    document.getElementById('add-first-source').addEventListener('click', function() {
      showAddSourceModal();
    });
  } else {
    // 渲染情报源卡片
    sources.forEach(source => {
      const card = createSourceCard(source);
      container.appendChild(card);
    });
  }
}

// 显示添加情报源模态框
function showAddSourceModal() {
  console.log('显示添加情报源模态框');
  alert('添加情报源功能将在这里实现');
}

// 保存情报源
function saveIntelligenceSource(sourceData) {
  try {
    // 显示加载状态
    window.showLoading('正在保存情报源...');
    
    // 生成唯一ID
    sourceData.id = Date.now().toString();
    sourceData.lastUpdated = Date.now();
    
    // 获取现有数据
    const sources = dataManager.getIntelligenceSources();
    
    // 添加新数据
    sources.push(sourceData);
    
    // 保存到本地存储
    dataManager.saveIntelligenceSources(sources);
    
    // 更新视图
    renderIntelligenceSources();
    
    // 隐藏加载状态并显示成功通知
    setTimeout(() => {
      window.hideLoading();
      console.log('情报源保存成功:', sourceData.name);
      showNotification('情报源创建成功！', 'success');
    }, 500); // 添加短暂延迟以展示加载效果
    
    return { success: true };
  } catch (error) {
    // 隐藏加载状态
    window.hideLoading();
    console.error('保存情报源失败:', error);
    showNotification('创建情报源失败，请重试', 'error');
    return { success: false, error: error.message };
  }
}

// 更新情报源
function updateIntelligenceSource(sourceId, updatedData) {
  try {
    // 显示加载状态
    window.showLoading('正在更新情报源...');
    
    // 获取现有数据
    const sources = dataManager.getIntelligenceSources();
    
    // 查找并更新
    const index = sources.findIndex(s => s.id === sourceId);
    if (index === -1) {
      throw new Error('未找到指定的情报源');
    }
    
    // 更新数据
    sources[index] = { ...sources[index], ...updatedData, lastUpdated: Date.now() };
    
    // 保存到本地存储
    dataManager.saveIntelligenceSources(sources);
    
    // 更新视图
    renderIntelligenceSources();
    
    // 隐藏加载状态并显示成功通知
    setTimeout(() => {
      window.hideLoading();
      console.log('情报源更新成功:', sourceId);
      showNotification('情报源更新成功！', 'success');
    }, 500); // 添加短暂延迟以展示加载效果
    
    return { success: true };
  } catch (error) {
    // 隐藏加载状态
    window.hideLoading();
    console.error('更新情报源失败:', error);
    showNotification('更新情报源失败，请重试', 'error');
    return { success: false, error: error.message };
  }
}

// 删除情报源
function deleteIntelligenceSource(sourceId) {
  // 显示确认对话框
  if (confirm('确定要删除这个情报源吗？此操作不可恢复。')) {
    try {
      // 显示加载状态
      window.showLoading('正在删除情报源...');
      
      // 获取现有数据
      const sources = dataManager.getIntelligenceSources();
      
      // 过滤掉要删除的项目
      const updatedSources = sources.filter(s => s.id !== sourceId);
      
      // 保存到本地存储
      dataManager.saveIntelligenceSources(updatedSources);
      
      // 更新视图
      renderIntelligenceSources();
      
      // 隐藏加载状态并显示成功通知
      setTimeout(() => {
        window.hideLoading();
        console.log('情报源删除成功:', sourceId);
        showNotification('情报源删除成功！', 'success');
      }, 500); // 添加短暂延迟以展示加载效果
      
      return { success: true };
    } catch (error) {
      // 隐藏加载状态
      window.hideLoading();
      console.error('删除情报源失败:', error);
      showNotification('删除情报源失败，请重试', 'error');
      return { success: false, error: error.message };
    }
  } else {
    return { success: false, canceled: true };
  }
}

// 创建情报源卡片
function createSourceCard(source) {
  const card = document.createElement('div');
  card.className = 'source-card';
  
  // 获取状态样式
  const statusStyles = getStatusStyles(source.status);
  
  // 构建卡片HTML
  card.innerHTML = `
    <div class="source-card-header">
      <div class="flex justify-between items-start">
        <div>
          <h3 class="font-semibold text-gray-800 mb-1">${source.name}</h3>
          <span class="text-sm text-gray-500">${source.type}</span>
        </div>
        <span class="score-badge score-${source.status}">${source.qualityScore}</span>
      </div>
    </div>
    <div class="source-card-body">
      <div class="mb-3">
        <div class="flex justify-between text-xs text-gray-500 mb-1">
          <span>质量状态</span>
          <span class="${statusStyles.color}">${statusStyles.label}</span>
        </div>
        <div class="progress">
          <div class="progress-bar" style="width: ${source.qualityScore}%; background-color: ${getStatusColor(source.status)}"></div>
        </div>
      </div>
      <div class="grid grid-cols-2 gap-2 text-sm">
        <div>
          <p class="text-gray-500">更新频率</p>
          <p class="font-medium text-gray-800">${source.updateFrequency}</p>
        </div>
        <div>
          <p class="text-gray-500">覆盖范围</p>
          <p class="font-medium text-gray-800">${source.coverage}</p>
        </div>
      </div>
    </div>
    <div class="source-card-footer">
      <span class="text-xs text-gray-500">更新于: ${formatTime(source.lastUpdated)}</span>
      <div class="flex space-x-2">
        <button class="text-blue-500 hover:text-blue-600" data-source-id="${source.id}" data-action="edit">
          <i class="fa fa-pencil"></i>
        </button>
        <button class="text-gray-400 hover:text-gray-600" data-source-id="${source.id}" data-action="more">
          <i class="fa fa-ellipsis-v"></i>
        </button>
      </div>
    </div>
  `;
  
  // 绑定卡片事件
  bindCardEvents(card, source);
  
  return card;
}

// 获取状态对应的颜色
function getStatusColor(status) {
  switch (status) {
    case 'excellent': return '#10b981';
    case 'good': return '#3b82f6';
    case 'normal': return '#f59e0b';
    case 'warning': return '#ef4444';
    default: return '#64748b';
  }
}

// 绑定卡片事件
function bindCardEvents(card, source) {
  // 编辑按钮事件
  const editBtn = card.querySelector('[data-action="edit"]');
  if (editBtn) {
    editBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      showEditSourceModal(source);
    });
  }
  
  // 评估按钮事件
  const evalBtn = card.querySelector('[data-action="evaluate"]');
  if (evalBtn) {
    evalBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      showEvaluationModal(source);
    });
  }
  
  // 下钻分析按钮事件
  const drillBtn = card.querySelector('[data-action="drill-down"]');
  if (drillBtn) {
    drillBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      showQualityDrillDown(source);
    });
  }
  
  // 卡片点击事件 - 显示详情
  card.addEventListener('click', function() {
    showSourceDetails(source);
  });
}

// 显示质量评分下钻分析
function showQualityDrillDown(source) {
  console.log('显示质量评分下钻分析:', source.name);
  
  // 创建模态框
  const modal = document.createElement('div');
  modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
  modal.innerHTML = `
    <div class="bg-white rounded-lg shadow-lg max-w-2xl w-full max-h-[80vh] overflow-y-auto">
      <div class="p-6">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-semibold">${source.name} - 质量评分详情</h3>
          <button class="close-modal text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        
        <!-- 质量评分概览 -->
        <div class="mb-6 text-center">
          <div class="text-4xl font-bold ${getStatusColor(source.qualityScore)}">${source.qualityScore}</div>
          <div class="text-sm text-gray-500">综合评分</div>
        </div>
        
        <!-- 各维度评分详情 -->
        <div class="mb-6">
          <h4 class="text-lg font-medium mb-3">评分构成</h4>
          <div class="space-y-4">
            ${Object.entries(source.qualityBreakdown).map(([factor, score]) => `
              <div>
                <div class="flex justify-between mb-1">
                  <span class="text-sm font-medium">${getFactorName(factor)}</span>
                  <span class="text-sm ${getScoreColor(score)}">${score}</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div class="${getScoreColor(score)} bg-opacity-70 h-2 rounded-full" style="width: ${score}%"></div>
                </div>
              </div>
            `).join('')}
          </div>
        </div>
        
        <!-- 质量雷达图 -->
        <div class="mb-6">
          <h4 class="text-lg font-medium mb-3">质量维度雷达图</h4>
          <div class="w-full h-64">
            <canvas id="drilldown-radar-chart"></canvas>
          </div>
        </div>
        
        <!-- 改进建议 -->
        <div class="mb-4">
          <h4 class="text-lg font-medium mb-2">改进建议</h4>
          <div class="bg-blue-50 p-4 rounded-lg">
            <p class="text-sm text-gray-700">${generateImprovementSuggestions(source.qualityBreakdown)}</p>
          </div>
        </div>
      </div>
    </div>
  `;
  
  // 添加到页面
  document.body.appendChild(modal);
  
  // 初始化雷达图
  initDrilldownRadarChart(source.qualityBreakdown);
  
  // 绑定关闭事件
  modal.querySelector('.close-modal').addEventListener('click', function() {
    document.body.removeChild(modal);
  });
  
  // 点击模态框背景关闭
  modal.addEventListener('click', function(e) {
    if (e.target === modal) {
      document.body.removeChild(modal);
    }
  });
}

// 初始化下钻分析雷达图
function initDrilldownRadarChart(qualityBreakdown) {
  const ctx = document.getElementById('drilldown-radar-chart');
  if (!ctx) return;
  
  // 准备数据
  const labels = Object.keys(qualityBreakdown).map(factor => getFactorName(factor));
  const data = Object.values(qualityBreakdown);
  
  // 保存图表实例到window对象，以便后续更新
  window.qualityChart = new Chart(ctx, {
    type: 'radar',
    data: {
      labels: labels,
      datasets: [{
        label: '质量评分',
        data: data,
        backgroundColor: 'rgba(59, 130, 246, 0.2)',
        borderColor: 'rgba(59, 130, 246, 1)',
        borderWidth: 2,
        pointBackgroundColor: 'rgba(59, 130, 246, 1)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: 'rgba(59, 130, 246, 1)'
      }]
    },
    options: {
      scales: {
        r: {
          beginAtZero: true,
          max: 100,
          ticks: {
            stepSize: 20
          }
        }
      },
      plugins: {
        legend: {
          display: true,
          position: 'top'
        }
      }
    }
  });
}

// 获取评估因子中文名称
function getFactorName(factor) {
  const names = {
    timeliness: '及时性',
    accuracy: '准确性',
    richness: '丰富性',
    uniqueness: '差异性',
    hitRate: '命中率'
  };
  return names[factor] || factor;
}

// 根据分数获取颜色
function getScoreColor(score) {
  if (score >= 85) return 'text-green-600';
  if (score >= 70) return 'text-blue-600';
  if (score >= 50) return 'text-yellow-600';
  return 'text-red-600';
}

// 生成改进建议
function generateImprovementSuggestions(breakdown) {
  const suggestions = [];
  
  // 找出分数最低的两个因子
  const sortedFactors = Object.entries(breakdown)
    .sort(([,a], [,b]) => a - b)
    .slice(0, 2);
  
  sortedFactors.forEach(([factor, score]) => {
    const factorSuggestions = {
      timeliness: '建议提高情报更新频率，缩短时间延迟。',
      accuracy: '需要加强情报验证机制，减少误报率。',
      richness: '应增加情报字段完整性和上下文信息深度。',
      uniqueness: '需优化去重算法，提高情报源差异性。',
      hitRate: '建议调整命中率统计方法，减少无效情报。'
    };
    
    if (factorSuggestions[factor]) {
      suggestions.push(`${getFactorName(factor)}评分(${score})偏低。${factorSuggestions[factor]}`);
    }
  });
  
  if (suggestions.length === 0) {
    return '当前情报源质量表现良好，建议保持现有运营策略。';
  }
  
  return suggestions.join(' ');
}

// 显示情报源详情
function showSourceDetails(source) {
  // 创建详情内容
  const content = `
    <div class="space-y-4">
      <div>
        <h3 class="text-xl font-bold text-gray-800">${source.name}</h3>
        <p class="text-gray-600">${source.type}</p>
      </div>
      
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="bg-gray-50 p-4 rounded-lg">
          <p class="text-sm text-gray-500">质量评分</p>
          <p class="text-2xl font-bold ${getStatusStyles(source.status).color}">${source.qualityScore}/100</p>
        </div>
        <div class="bg-gray-50 p-4 rounded-lg">
          <p class="text-sm text-gray-500">状态</p>
          <p class="text-lg font-medium ${getStatusStyles(source.status).color}">${getStatusStyles(source.status).label}</p>
        </div>
        <div class="bg-gray-50 p-4 rounded-lg">
          <p class="text-sm text-gray-500">最后更新</p>
          <p class="text-lg font-medium">${formatTime(source.lastUpdated)}</p>
        </div>
      </div>
      
      <div>
        <h4 class="font-semibold text-gray-700 mb-2">评估因子明细</h4>
        <div class="space-y-3">
          <div>
            <div class="flex justify-between text-sm mb-1">
              <span>及时性</span>
              <span>${source.factors.timeliness}%</span>
            </div>
            <div class="progress">
              <div class="progress-bar" style="width: ${source.factors.timeliness}%; background-color: #3b82f6"></div>
            </div>
          </div>
          <div>
            <div class="flex justify-between text-sm mb-1">
              <span>命中率</span>
              <span>${source.factors.hitRate}%</span>
            </div>
            <div class="progress">
              <div class="progress-bar" style="width: ${source.factors.hitRate}%; background-color: #10b981"></div>
            </div>
          </div>
          <div>
            <div class="flex justify-between text-sm mb-1">
              <span>差异性</span>
              <span>${source.factors.diversity}%</span>
            </div>
            <div class="progress">
              <div class="progress-bar" style="width: ${source.factors.diversity}%; background-color: #f59e0b"></div>
            </div>
          </div>
          <div>
            <div class="flex justify-between text-sm mb-1">
              <span>丰富性</span>
              <span>${source.factors.richness}%</span>
            </div>
            <div class="progress">
              <div class="progress-bar" style="width: ${source.factors.richness}%; background-color: #8b5cf6"></div>
            </div>
          </div>
          <div>
            <div class="flex justify-between text-sm mb-1">
              <span>准确性</span>
              <span>${source.factors.accuracy}%</span>
            </div>
            <div class="progress">
              <div class="progress-bar" style="width: ${source.factors.accuracy}%; background-color: #ec4899"></div>
            </div>
          </div>
        </div>
      </div>
      
      <div>
        <h4 class="font-semibold text-gray-700 mb-2">详细信息</h4>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <p class="text-sm text-gray-500">更新频率</p>
            <p class="font-medium">${source.updateFrequency}</p>
          </div>
          <div>
            <p class="text-sm text-gray-500">覆盖范围</p>
            <p class="font-medium">${source.coverage}</p>
          </div>
          <div>
            <p class="text-sm text-gray-500">可靠性</p>
            <p class="font-medium">${source.reliability}</p>
          </div>
          <div>
            <p class="text-sm text-gray-500">ID</p>
            <p class="font-medium">${source.id}</p>
          </div>
        </div>
      </div>
    </div>
  `;
  
  // 在实际应用中，这里应该打开一个模态框或切换到详情视图
  // 为了演示，我们简单地替换主内容区域
  const contentArea = document.getElementById('content-area');
  if (contentArea) {
    contentArea.innerHTML = `
      <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-xl font-bold text-gray-800">情报源详情</h2>
          <button id="backToList" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg">
            返回列表
          </button>
        </div>
        ${content}
        <div class="mt-6 flex justify-end space-x-3">
          <button id="exportSourceData" class="btn btn-secondary">导出数据</button>
          <button id="editSourceFromDetail" class="btn btn-primary">编辑情报源</button>
        </div>
      </div>
    `;
    
    // 绑定返回按钮事件
    document.getElementById('backToList').addEventListener('click', function() {
      // 重新构建整个列表视图的HTML结构，而不仅仅调用renderIntelligenceSources
      contentArea.innerHTML = `
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-4">
          <h2 class="text-lg font-semibold mb-3">情报源概览</h2>
          <div class="flex flex-wrap gap-4">
            <div class="flex-1 min-w-[200px] bg-blue-50 rounded-lg p-4">
              <p class="text-gray-600 text-sm">总情报源</p>
              <p class="text-2xl font-bold text-blue-600">42</p>
            </div>
            <div class="flex-1 min-w-[200px] bg-green-50 rounded-lg p-4">
              <p class="text-gray-600 text-sm">优质情报源</p>
              <p class="text-2xl font-bold text-green-600">18</p>
            </div>
            <div class="flex-1 min-w-[200px] bg-yellow-50 rounded-lg p-4">
              <p class="text-gray-600 text-sm">需关注情报源</p>
              <p class="text-2xl font-bold text-yellow-600">6</p>
            </div>
            <div class="flex-1 min-w-[200px] bg-red-50 rounded-lg p-4">
              <p class="text-gray-600 text-sm">最近更新</p>
              <p class="text-2xl font-bold text-red-600">30分钟前</p>
            </div>
          </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold">情报源列表</h2>
            <div class="flex items-center space-x-2">
              <select class="border border-gray-300 rounded-lg px-3 py-1 text-sm">
                <option>按质量评分排序</option>
                <option>按更新时间排序</option>
                <option>按类型排序</option>
              </select>
              <button class="text-gray-400 hover:text-gray-600">
                <i class="fa fa-refresh"></i>
              </button>
            </div>
          </div>
          
          <!-- 情报源卡片容器 -->
          <div id="intelligence-sources" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <!-- 情报源卡片将由JavaScript动态生成 -->
          </div>
        </div>
      `;
      
      // 现在调用renderIntelligenceSources来填充情报源卡片
      renderIntelligenceSources();
    });
    
    // 绑定编辑按钮事件
    document.getElementById('editSourceFromDetail').addEventListener('click', function() {
      // 调用已有的编辑模态框函数
      showEditSourceModal(source);
      
      // 修改编辑模态框的回调逻辑，编辑完成后返回详情页
      const originalSubmitHandler = document.getElementById('edit-source-form').onsubmit;
      document.getElementById('edit-source-form').onsubmit = function(e) {
        e.preventDefault();
        if (originalSubmitHandler) {
          originalSubmitHandler.apply(this, arguments);
        }
        
        // 获取更新后的源数据
        const updatedSource = dataManager.getIntelligenceSource(source.id);
        // 重新显示详情页，显示更新后的数据
        showSourceDetails(updatedSource);
        
        // 显示成功通知
        showNotification('情报源更新成功！', 'success');
      };
    });
    
    // 绑定导出按钮事件
    document.getElementById('exportSourceData').addEventListener('click', function() {
      // 导出单个情报源数据为JSON格式
      const jsonData = JSON.stringify(source, null, 2);
      const blob = new Blob([jsonData], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      
      // 创建下载链接
      const a = document.createElement('a');
      a.href = url;
      a.download = `情报源_${source.name}_${new Date().toISOString().split('T')[0]}.json`;
      a.click();
      
      // 释放URL对象
      URL.revokeObjectURL(url);
      
      // 显示成功通知
      showNotification('情报源数据导出成功！', 'success');
    });
  }
}

// 初始化质量分布图表
function initQualityChart() {
  const ctx = document.getElementById('qualityChart');
  if (!ctx) return;
  
  // 获取数据
  const sources = dataManager.getIntelligenceSources();
  const statusCounts = {
    excellent: sources.filter(s => s.status === 'excellent').length,
    good: sources.filter(s => s.status === 'good').length,
    normal: sources.filter(s => s.status === 'normal').length,
    warning: sources.filter(s => s.status === 'warning').length
  };
  
  // 安全检查：确保Chart对象存在
  if (typeof Chart === 'undefined' || typeof Chart !== 'function') {
    console.warn('Chart.js未正确加载，使用简单DOM渲染替代');
    // 使用简单的DOM元素替代图表
    const container = ctx.parentElement;
    container.innerHTML = `
      <div class="p-4 bg-gray-50 rounded-lg">
        <h4 class="font-medium mb-2">情报源质量分布</h4>
        <div class="grid grid-cols-2 gap-2">
          <div class="flex items-center p-2 rounded-md" style="background-color: rgba(16, 185, 129, 0.1)">
            <div class="w-3 h-3 rounded-full bg-[#10b981] mr-2"></div>
            <span class="text-sm">优秀: ${statusCounts.excellent}</span>
          </div>
          <div class="flex items-center p-2 rounded-md" style="background-color: rgba(59, 130, 246, 0.1)">
            <div class="w-3 h-3 rounded-full bg-[#3b82f6] mr-2"></div>
            <span class="text-sm">良好: ${statusCounts.good}</span>
          </div>
          <div class="flex items-center p-2 rounded-md" style="background-color: rgba(245, 158, 11, 0.1)">
            <div class="w-3 h-3 rounded-full bg-[#f59e0b] mr-2"></div>
            <span class="text-sm">一般: ${statusCounts.normal}</span>
          </div>
          <div class="flex items-center p-2 rounded-md" style="background-color: rgba(239, 68, 68, 0.1)">
            <div class="w-3 h-3 rounded-full bg-[#ef4444] mr-2"></div>
            <span class="text-sm">需关注: ${statusCounts.warning}</span>
          </div>
        </div>
      </div>
    `;
    return;
  }
  
  // 尝试创建图表
  try {
    // 保存图表实例到window对象，以便后续更新
    window.qualityChart = new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels: ['优秀', '良好', '一般', '需关注'],
        datasets: [{
          data: [statusCounts.excellent, statusCounts.good, statusCounts.normal, statusCounts.warning],
          backgroundColor: [
            '#10b981', // green
            '#3b82f6', // blue
            '#f59e0b', // yellow
            '#ef4444'  // red
          ],
          borderWidth: 0
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'bottom',
            labels: {
              boxWidth: 12,
              padding: 15
            }
          }
        },
        cutout: '70%'
      }
    });
  } catch (error) {
    console.error('创建图表时出错:', error);
    // 降级到简单DOM渲染
    const container = ctx.parentElement;
    container.innerHTML = `<div class="p-4 bg-gray-50 rounded-lg text-center">图表加载失败，请刷新页面重试</div>`;
  }
}

// 绑定导航事件
function bindNavigationEvents() {
  const navItems = document.querySelectorAll('nav a');
  navItems.forEach(item => {
    item.addEventListener('click', function(e) {
      e.preventDefault();
      
      // 获取当前导航项文本
      const navText = this.textContent.trim();
      
      // 移除所有激活状态
      navItems.forEach(i => i.classList.remove('bg-blue-50', 'text-blue-600', 'font-medium'));
      navItems.forEach(i => i.classList.add('hover:bg-gray-100'));
      
      // 添加当前激活状态
      this.classList.add('bg-blue-50', 'text-blue-600', 'font-medium');
      this.classList.remove('hover:bg-gray-100');
      
      // 强制刷新对应内容
      switchContent(navText);
      
      // 特殊处理情报源管理tab，确保页面内容完全刷新
      if (navText === '情报源管理') {
        // 清空内容区域确保完全重新渲染
        const contentArea = document.getElementById('content-area');
        if (contentArea) {
          // 先清空整个内容区域
          contentArea.innerHTML = '';
          
          // 确保intelligence-sources容器存在
          const sourcesContainer = document.createElement('div');
          sourcesContainer.id = 'intelligence-sources';
          sourcesContainer.className = 'grid grid-cols-1 gap-6 mt-6';
          contentArea.appendChild(sourcesContainer);
          
          // 确保右侧面板的导出按钮容器也存在
          const rightPanel = document.querySelector('.right-panel');
          if (rightPanel) {
            const exportBtnContainer = rightPanel.querySelector('#export-data-btn')?.parentElement;
            if (!exportBtnContainer) {
              // 如果导出按钮不存在，创建一个简单的容器
              const container = document.createElement('div');
              container.className = 'mt-6';
              const exportBtn = document.createElement('button');
              exportBtn.id = 'export-data-btn';
              exportBtn.className = 'px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600';
              exportBtn.textContent = '导出数据';
              container.appendChild(exportBtn);
              rightPanel.appendChild(container);
            }
          }
        }
        
        // 重新渲染情报源列表
        setTimeout(() => {
          renderIntelligenceSources();
        }, 10);
      }
    });
  });
}

// 切换内容视图
function switchContent(viewName) {
  const contentArea = document.getElementById('content-area');
  if (!contentArea) return;
  
  switch(viewName) {
    case '情报源管理':
      renderIntelligenceSources();
      break;
    case '质量评估配置':
      renderEvaluationConfigurationView();
      break;
    case '专题管理':
      renderTopicsView();
      break;
    case 'AI解读':
      renderAIInsightsView();
      break;
    case '报告导出':
      renderReportsView();
      break;
  }
}

// 渲染质量评估配置视图
function renderEvaluationConfigurationView() {
  const contentArea = document.getElementById('content-area');
  if (!contentArea) return;
  
  const models = dataManager.getEvaluationModels();
  const currentModel = models[0]; // 默认使用第一个模型
  
  contentArea.innerHTML = `
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-4">
      <h2 class="text-xl font-bold text-gray-800 mb-4">质量评估模型配置</h2>
      
      <div class="mb-6">
        <div class="flex flex-wrap gap-2 mb-4">
          ${models.map(model => `
            <button class="px-4 py-2 rounded-lg ${model.isDefault ? 'bg-blue-50 text-blue-600 border border-blue-200' : 'bg-gray-50 text-gray-600 border border-gray-200'} hover:bg-gray-100" data-model-id="${model.id}">
              ${model.name}
              ${model.isDefault ? '<span class="ml-2 text-xs bg-blue-100 text-blue-600 px-2 py-0.5 rounded-full">默认</span>' : ''}
            </button>
          `).join('')}
          <button class="px-4 py-2 rounded-lg bg-gray-50 text-gray-600 border border-dashed border-gray-300 hover:bg-gray-100">
            <i class="fa fa-plus mr-1"></i>新建模型
          </button>
        </div>
      </div>
      
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <!-- 及时性因子配置 -->
        <div class="border border-gray-200 rounded-xl p-4">
          <h3 class="font-semibold text-gray-800 mb-3">及时性因子</h3>
          <div class="mb-4">
            <div class="flex justify-between text-sm mb-1">
              <span>权重</span>
              <span id="timeliness-weight">${currentModel.factors.timeliness.weight}%</span>
            </div>
            <input type="range" min="0" max="100" value="${currentModel.factors.timeliness.weight}" class="factor-weight" data-factor="timeliness">
          </div>
          <div class="space-y-3">
            <div>
              <label class="block text-sm text-gray-600 mb-1">时间延迟阈值</label>
              <input type="number" value="${currentModel.factors.timeliness.delayThreshold}" class="w-full input" data-setting="delayThreshold">
              <p class="text-xs text-gray-500 mt-1">分钟</p>
            </div>
            <div>
              <label class="block text-sm text-gray-600 mb-1">更新频率要求</label>
              <select class="w-full input" data-setting="updateFrequency">
                <option value="realtime" ${currentModel.factors.timeliness.updateFrequency === 'realtime' ? 'selected' : ''}>实时</option>
                <option value="hourly" ${currentModel.factors.timeliness.updateFrequency === 'hourly' ? 'selected' : ''}>每小时</option>
                <option value="daily" ${currentModel.factors.timeliness.updateFrequency === 'daily' ? 'selected' : ''}>每日</option>
                <option value="weekly" ${currentModel.factors.timeliness.updateFrequency === 'weekly' ? 'selected' : ''}>每周</option>
              </select>
            </div>
          </div>
        </div>
        
        <!-- 命中率因子配置 -->
        <div class="border border-gray-200 rounded-xl p-4">
          <h3 class="font-semibold text-gray-800 mb-3">命中率因子</h3>
          <div class="mb-4">
            <div class="flex justify-between text-sm mb-1">
              <span>权重</span>
              <span id="hitRate-weight">${currentModel.factors.hitRate.weight}%</span>
            </div>
            <input type="range" min="0" max="100" value="${currentModel.factors.hitRate.weight}" class="factor-weight" data-factor="hitRate">
          </div>
          <div class="space-y-3">
            <div>
              <label class="block text-sm text-gray-600 mb-1">历史命中率统计</label>
              <input type="number" step="0.01" value="${currentModel.factors.hitRate.historyStats}" class="w-full input" data-setting="historyStats">
            </div>
            <div>
              <label class="block text-sm text-gray-600 mb-1">误报率关联</label>
              <input type="range" min="0" max="1" step="0.01" value="${currentModel.factors.hitRate.falsePositiveRate}" class="w-full" data-setting="falsePositiveRate">
              <p class="text-xs text-gray-500 mt-1">${currentModel.factors.hitRate.falsePositiveRate}</p>
            </div>
          </div>
        </div>
        
        <!-- 差异性因子配置 -->
        <div class="border border-gray-200 rounded-xl p-4">
          <h3 class="font-semibold text-gray-800 mb-3">差异性因子</h3>
          <div class="mb-4">
            <div class="flex justify-between text-sm mb-1">
              <span>权重</span>
              <span id="diversity-weight">${currentModel.factors.diversity.weight}%</span>
            </div>
            <input type="range" min="0" max="100" value="${currentModel.factors.diversity.weight}" class="factor-weight" data-factor="diversity">
          </div>
          <div class="space-y-3">
            <div>
              <label class="block text-sm text-gray-600 mb-1">去重算法</label>
              <select class="w-full input" data-setting="dedupAlgorithm">
                <option value="cosine" ${currentModel.factors.diversity.dedupAlgorithm === 'cosine' ? 'selected' : ''}>余弦相似度</option>
                <option value="jaccard" ${currentModel.factors.diversity.dedupAlgorithm === 'jaccard' ? 'selected' : ''}>Jaccard相似度</option>
                <option value="levenshtein" ${currentModel.factors.diversity.dedupAlgorithm === 'levenshtein' ? 'selected' : ''}>编辑距离</option>
              </select>
            </div>
            <div>
              <label class="block text-sm text-gray-600 mb-1">相似度阈值</label>
              <input type="range" min="0" max="1" step="0.01" value="${currentModel.factors.diversity.similarityThreshold}" class="w-full" data-setting="similarityThreshold">
              <p class="text-xs text-gray-500 mt-1">${currentModel.factors.diversity.similarityThreshold}</p>
            </div>
          </div>
        </div>
        
        <!-- 丰富性因子配置 -->
        <div class="border border-gray-200 rounded-xl p-4">
          <h3 class="font-semibold text-gray-800 mb-3">丰富性因子</h3>
          <div class="mb-4">
            <div class="flex justify-between text-sm mb-1">
              <span>权重</span>
              <span id="richness-weight">${currentModel.factors.richness.weight}%</span>
            </div>
            <input type="range" min="0" max="100" value="${currentModel.factors.richness.weight}" class="factor-weight" data-factor="richness">
          </div>
          <div class="space-y-3">
            <div>
              <label class="block text-sm text-gray-600 mb-1">字段完整性要求</label>
              <input type="range" min="0" max="1" step="0.01" value="${currentModel.factors.richness.fieldCompleteness}" class="w-full" data-setting="fieldCompleteness">
              <p class="text-xs text-gray-500 mt-1">${currentModel.factors.richness.fieldCompleteness}</p>
            </div>
            <div>
              <label class="block text-sm text-gray-600 mb-1">上下文信息深度</label>
              <select class="w-full input" data-setting="contextDepth">
                <option value="low" ${currentModel.factors.richness.contextDepth === 'low' ? 'selected' : ''}>基础</option>
                <option value="medium" ${currentModel.factors.richness.contextDepth === 'medium' ? 'selected' : ''}>中等</option>
                <option value="high" ${currentModel.factors.richness.contextDepth === 'high' ? 'selected' : ''}>高级</option>
              </select>
            </div>
          </div>
        </div>
        
        <!-- 准确性因子配置 -->
        <div class="border border-gray-200 rounded-xl p-4">
          <h3 class="font-semibold text-gray-800 mb-3">准确性因子</h3>
          <div class="mb-4">
            <div class="flex justify-between text-sm mb-1">
              <span>权重</span>
              <span id="accuracy-weight">${currentModel.factors.accuracy.weight}%</span>
            </div>
            <input type="range" min="0" max="100" value="${currentModel.factors.accuracy.weight}" class="factor-weight" data-factor="accuracy">
          </div>
          <div class="space-y-3">
            <div>
              <label class="block text-sm text-gray-600 mb-1">验证机制</label>
              <select class="w-full input" data-setting="validationMethod">
                <option value="auto" ${currentModel.factors.accuracy.validationMethod === 'auto' ? 'selected' : ''}>自动验证</option>
                <option value="manual" ${currentModel.factors.accuracy.validationMethod === 'manual' ? 'selected' : ''}>人工审核</option>
                <option value="both" ${currentModel.factors.accuracy.validationMethod === 'both' ? 'selected' : ''}>两者结合</option>
              </select>
            </div>
            <div>
              <label class="block text-sm text-gray-600 mb-1">置信度阈值</label>
              <input type="range" min="0" max="1" step="0.01" value="${currentModel.factors.accuracy.confidenceThreshold}" class="w-full" data-setting="confidenceThreshold">
              <p class="text-xs text-gray-500 mt-1">${currentModel.factors.accuracy.confidenceThreshold}</p>
            </div>
          </div>
        </div>
        
        <!-- 配置结果预览 -->
        <div class="border border-gray-200 rounded-xl p-4 bg-blue-50">
          <h3 class="font-semibold text-gray-800 mb-3">配置预览</h3>
          <div class="space-y-3 mb-4">
            <div class="flex justify-between text-sm">
              <span>总权重</span>
              <span id="total-weight" class="font-medium">100%</span>
            </div>
            <div class="h-40">
              <canvas id="factorRadarChart"></canvas>
            </div>
          </div>
          <div class="space-y-2">
            <button class="w-full btn btn-primary">应用配置</button>
            <button class="w-full btn btn-secondary">保存为模板</button>
            <button class="w-full text-sm text-blue-500 hover:text-blue-600">导入/导出</button>
          </div>
        </div>
      </div>
    </div>
  `;
  
  // 初始化雷达图
  initFactorRadarChart(currentModel);
  
  // 绑定因子权重滑动条事件
  bindFactorWeightEvents();
  
  // 绑定模型选择按钮点击事件
  bindModelSelectionEvents();
}

// 绑定模型选择按钮点击事件
function bindModelSelectionEvents() {
  const modelButtons = document.querySelectorAll('[data-model-id]');
  modelButtons.forEach(button => {
    button.addEventListener('click', function() {
      const modelId = this.getAttribute('data-model-id');
      const model = dataManager.getEvaluationModel(modelId);
      
      if (model) {
        // 更新按钮样式
        modelButtons.forEach(btn => {
          btn.classList.remove('bg-blue-50', 'text-blue-600', 'border-blue-200');
          btn.classList.add('bg-gray-50', 'text-gray-600', 'border-gray-200');
        });
        this.classList.remove('bg-gray-50', 'text-gray-600', 'border-gray-200');
        this.classList.add('bg-blue-50', 'text-blue-600', 'border-blue-200');
        
        // 更新配置列表中的数据
        updateConfigurationView(model);
        
        console.log('切换到模型:', model.name);
      }
    });
  });
}

// 更新配置视图
function updateConfigurationView(model) {
  // 更新及时性因子配置
  document.getElementById('timeliness-weight').textContent = `${model.factors.timeliness.weight}%`;
  const timelinessSlider = document.querySelector('.factor-weight[data-factor="timeliness"]');
  if (timelinessSlider) {
    timelinessSlider.value = model.factors.timeliness.weight;
  }
  const delayThresholdInput = document.querySelector('[data-setting="delayThreshold"]');
  if (delayThresholdInput) {
    delayThresholdInput.value = model.factors.timeliness.delayThreshold;
  }
  const updateFrequencySelect = document.querySelector('[data-setting="updateFrequency"]');
  if (updateFrequencySelect) {
    updateFrequencySelect.value = model.factors.timeliness.updateFrequency;
  }
  
  // 更新命中率因子配置
  document.getElementById('hitRate-weight').textContent = `${model.factors.hitRate.weight}%`;
  const hitRateSlider = document.querySelector('.factor-weight[data-factor="hitRate"]');
  if (hitRateSlider) {
    hitRateSlider.value = model.factors.hitRate.weight;
  }
  const historyStatsInput = document.querySelector('[data-setting="historyStats"]');
  if (historyStatsInput) {
    historyStatsInput.value = model.factors.hitRate.historyStats;
  }
  const falsePositiveRateInput = document.querySelector('[data-setting="falsePositiveRate"]');
  if (falsePositiveRateInput) {
    falsePositiveRateInput.value = model.factors.hitRate.falsePositiveRate;
    // 更新显示的误报率值
    const falsePositiveRateValue = falsePositiveRateInput.nextElementSibling;
    if (falsePositiveRateValue && falsePositiveRateValue.tagName === 'P') {
      falsePositiveRateValue.textContent = model.factors.hitRate.falsePositiveRate;
    }
  }
  
  // 更新差异性因子配置
  document.getElementById('diversity-weight').textContent = `${model.factors.diversity.weight}%`;
  const diversitySlider = document.querySelector('.factor-weight[data-factor="diversity"]');
  if (diversitySlider) {
    diversitySlider.value = model.factors.diversity.weight;
  }
  const dedupAlgorithmSelect = document.querySelector('[data-setting="dedupAlgorithm"]');
  if (dedupAlgorithmSelect) {
    dedupAlgorithmSelect.value = model.factors.diversity.dedupAlgorithm;
  }
  const similarityThresholdInput = document.querySelector('[data-setting="similarityThreshold"]');
  if (similarityThresholdInput) {
    similarityThresholdInput.value = model.factors.diversity.similarityThreshold;
    // 更新显示的相似度阈值
    const similarityThresholdValue = similarityThresholdInput.nextElementSibling;
    if (similarityThresholdValue && similarityThresholdValue.tagName === 'P') {
      similarityThresholdValue.textContent = model.factors.diversity.similarityThreshold;
    }
  }
  
  // 更新丰富性因子配置
  document.getElementById('richness-weight').textContent = `${model.factors.richness.weight}%`;
  const richnessSlider = document.querySelector('.factor-weight[data-factor="richness"]');
  if (richnessSlider) {
    richnessSlider.value = model.factors.richness.weight;
  }
  const fieldCompletenessInput = document.querySelector('[data-setting="fieldCompleteness"]');
  if (fieldCompletenessInput) {
    fieldCompletenessInput.value = model.factors.richness.fieldCompleteness;
    // 更新显示的字段完整性值
    const fieldCompletenessValue = fieldCompletenessInput.nextElementSibling;
    if (fieldCompletenessValue && fieldCompletenessValue.tagName === 'P') {
      fieldCompletenessValue.textContent = model.factors.richness.fieldCompleteness;
    }
  }
  const contextDepthSelect = document.querySelector('[data-setting="contextDepth"]');
  if (contextDepthSelect) {
    contextDepthSelect.value = model.factors.richness.contextDepth;
  }
  
  // 更新准确性因子配置
  document.getElementById('accuracy-weight').textContent = `${model.factors.accuracy.weight}%`;
  const accuracySlider = document.querySelector('.factor-weight[data-factor="accuracy"]');
  if (accuracySlider) {
    accuracySlider.value = model.factors.accuracy.weight;
  }
  const validationMethodSelect = document.querySelector('[data-setting="validationMethod"]');
  if (validationMethodSelect) {
    validationMethodSelect.value = model.factors.accuracy.validationMethod;
  }
  const confidenceThresholdInput = document.querySelector('[data-setting="confidenceThreshold"]');
  if (confidenceThresholdInput) {
    confidenceThresholdInput.value = model.factors.accuracy.confidenceThreshold;
    // 更新显示的置信度阈值
    const confidenceThresholdValue = confidenceThresholdInput.nextElementSibling;
    if (confidenceThresholdValue && confidenceThresholdValue.tagName === 'P') {
      confidenceThresholdValue.textContent = model.factors.accuracy.confidenceThreshold;
    }
  }
  
  // 重新初始化雷达图
  initFactorRadarChart(model);
  
  // 重新绑定因子权重滑动条事件
  bindFactorWeightEvents();
}

// 初始化因子雷达图
function initFactorRadarChart(model) {
  const ctx = document.getElementById('factorRadarChart');
  if (!ctx) return;
  
  new Chart(ctx, {
    type: 'radar',
    data: {
      labels: ['及时性', '命中率', '差异性', '丰富性', '准确性'],
      datasets: [{
        label: '权重分布',
        data: [
          model.factors.timeliness.weight,
          model.factors.hitRate.weight,
          model.factors.diversity.weight,
          model.factors.richness.weight,
          model.factors.accuracy.weight
        ],
        backgroundColor: 'rgba(59, 130, 246, 0.2)',
        borderColor: 'rgba(59, 130, 246, 0.8)',
        pointBackgroundColor: 'rgba(59, 130, 246, 1)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: 'rgba(59, 130, 246, 1)'
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        r: {
          beginAtZero: true,
          max: 50,
          ticks: {
            stepSize: 10
          }
        }
      }
    }
  });
}

// 绑定因子权重滑动条事件
function bindFactorWeightEvents() {
  const sliders = document.querySelectorAll('.factor-weight');
  sliders.forEach(slider => {
    slider.addEventListener('input', function() {
      const factor = this.getAttribute('data-factor');
      const value = this.value;
      
      // 更新显示的权重值
      document.getElementById(`${factor}-weight`).textContent = `${value}%`;
      
      // 计算总权重
      let totalWeight = 0;
      sliders.forEach(s => {
        totalWeight += parseInt(s.value);
      });
      
      const totalWeightElement = document.getElementById('total-weight');
      if (totalWeightElement) {
        totalWeightElement.textContent = `${totalWeight}%`;
        // 如果总权重不是100%，显示警告色
        if (totalWeight !== 100) {
          totalWeightElement.classList.add('text-yellow-600');
        } else {
          totalWeightElement.classList.remove('text-yellow-600');
        }
      }
    });
  });
}

// 渲染专题管理视图
function renderTopicsView() {
  const contentArea = document.getElementById('content-area');
  if (!contentArea) return;
  
  const topics = dataManager.getTopics();
  
  contentArea.innerHTML = `
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-4">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-bold text-gray-800">专题管理</h2>
      </div>
      
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-gray-200">
              <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600">专题名称</th>
              <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600">状态</th>
              <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600">情报源数量</th>
              <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600">最后更新</th>
              <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600">推送频率</th>
              <th class="py-3 px-4 text-right text-sm font-semibold text-gray-600">操作</th>
            </tr>
          </thead>
          <tbody>
            ${topics.map(topic => `
              <tr class="border-b border-gray-100 hover:bg-gray-50">
                <td class="py-4 px-4">
                  <div class="flex items-center">
                    <span class="font-medium text-gray-800">${topic.name}</span>
                    ${topic.newContentCount > 0 ? `<span class="ml-2 bg-red-100 text-red-600 text-xs px-2 py-1 rounded-full">${topic.newContentCount}个新</span>` : ''}
                  </div>
                </td>
                <td class="py-4 px-4">
                  <span class="tag ${topic.status === 'active' ? 'tag-success' : topic.status === 'pending' ? 'tag-warning' : 'tag-info'}">
                    ${topic.status === 'active' ? '活跃' : topic.status === 'pending' ? '待更新' : '已暂停'}
                  </span>
                </td>
                <td class="py-4 px-4 text-gray-700">${topic.sources.length}</td>
                <td class="py-4 px-4 text-gray-700">${formatTime(topic.lastUpdated)}</td>
                <td class="py-4 px-4 text-gray-700">${topic.pushFrequency}</td>
                <td class="py-4 px-4 text-right">
                  <div class="flex justify-end space-x-2">
                    <button class="text-blue-500 hover:text-blue-600" data-topic-id="${topic.id}" data-action="view">
                      <i class="fa fa-eye"></i>
                    </button>
                    <button class="text-green-500 hover:text-green-600" data-topic-id="${topic.id}" data-action="ai-analyze">
                      <i class="fa fa-robot"></i>
                    </button>
                    <button class="text-gray-400 hover:text-gray-600" data-topic-id="${topic.id}" data-action="more">
                      <i class="fa fa-ellipsis-v"></i>
                    </button>
                  </div>
                </td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>
    </div>
    
    <div class="grid grid-cols-1 md:grid-cols-1 gap-4">
      <!-- 热门专题模板 -->
      <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
      
      <!-- 热门专题模板 -->
      <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">热门专题模板</h3>
        <div class="space-y-3">
          <div class="p-3 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer">
            <h4 class="font-medium text-gray-800">APT活动监控</h4>
            <p class="text-sm text-gray-600">监控高级持续性威胁组织的最新活动</p>
          </div>
          <div class="p-3 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer">
            <h4 class="font-medium text-gray-800">零日漏洞追踪</h4>
            <p class="text-sm text-gray-600">追踪最新发现的零日漏洞和利用情况</p>
          </div>
          <div class="p-3 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer">
            <h4 class="font-medium text-gray-800">勒索软件预警</h4>
            <p class="text-sm text-gray-600">实时预警新型勒索软件威胁</p>
          </div>
        </div>
      </div>
    </div>
  `;
  
  // 绑定专题操作事件
  bindTopicEvents();
}

// 绑定专题操作事件
function bindTopicEvents() {
  const viewButtons = document.querySelectorAll('[data-action="view"]');
  viewButtons.forEach(button => {
    button.addEventListener('click', function() {
      const topicId = this.getAttribute('data-topic-id');
      const topic = dataManager.getTopic(topicId);
      if (topic) {
        showTopicDetails(topic);
      }
    });
  });
  
  const aiAnalyzeButtons = document.querySelectorAll('[data-action="ai-analyze"]');
  aiAnalyzeButtons.forEach(button => {
    button.addEventListener('click', function() {
      const topicId = this.getAttribute('data-topic-id');
      const topic = dataManager.getTopic(topicId);
      if (topic) {
        showAIAnalysis(topic);
      }
    });
  });
}

// 显示专题详情
function showTopicDetails(topic) {
  const contentArea = document.getElementById('content-area');
  if (!contentArea) return;
  
  const sources = dataManager.getIntelligenceSources();
  const topicSources = topic.sources.map(id => sources.find(s => s.id === id.toString())).filter(Boolean);
  
  contentArea.innerHTML = `
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-4">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-bold text-gray-800">${topic.name}</h2>
        <button id="backToTopics" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg">
          返回列表
        </button>
      </div>
      
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
        <div class="col-span-2">
          <h3 class="font-semibold text-gray-800 mb-2">专题描述</h3>
          <p class="text-gray-700">${topic.description}</p>
          
          <h3 class="font-semibold text-gray-800 mt-6 mb-3">关键词</h3>
          <div class="flex flex-wrap gap-2">
            ${topic.keywords.map(keyword => `
              <span class="bg-gray-100 text-gray-800 px-3 py-1 rounded-full text-sm">
                ${keyword}
              </span>
            `).join('')}
          </div>
        </div>
        
        <div class="space-y-4">
          <div class="bg-gray-50 p-4 rounded-lg">
            <p class="text-sm text-gray-500">状态</p>
            <p class="text-lg font-medium ${topic.status === 'active' ? 'text-green-600' : topic.status === 'pending' ? 'text-yellow-600' : 'text-gray-600'}">
              ${topic.status === 'active' ? '活跃' : topic.status === 'pending' ? '待更新' : '已暂停'}
            </p>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <p class="text-sm text-gray-500">推送频率</p>
            <p class="text-lg font-medium">${topic.pushFrequency}</p>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <p class="text-sm text-gray-500">最后更新</p>
            <p class="text-lg font-medium">${formatTime(topic.lastUpdated)}</p>
          </div>
          <button class="w-full btn btn-primary">
            <i class="fa fa-robot mr-2"></i>AI解读分析
          </button>
        </div>
      </div>
      
      <div class="mb-6">
        <h3 class="font-semibold text-gray-800 mb-3">相关情报源</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          ${topicSources.map(source => `
            <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
              <div class="flex justify-between items-start mb-2">
                <h4 class="font-medium text-gray-800">${source.name}</h4>
                <span class="score-badge score-${source.status}">${source.qualityScore}</span>
              </div>
              <p class="text-sm text-gray-600 mb-2">${source.type}</p>
              <div class="flex justify-between text-xs text-gray-500">
                <span>${source.reliability}</span>
                <span>${formatTime(source.lastUpdated)}</span>
              </div>
            </div>
          `).join('')}
        </div>
      </div>
      
      <div>
        <h3 class="font-semibold text-gray-800 mb-3">情报趋势分析</h3>
        <div class="h-64">
          <canvas id="topicTrendChart"></canvas>
        </div>
      </div>
    </div>
  `;
  
  // 初始化趋势图表
  initTopicTrendChart();
  
  // 绑定返回按钮事件
  document.getElementById('backToTopics').addEventListener('click', function() {
    renderTopicsView();
  });
}

// 初始化专题趋势图表
function initTopicTrendChart() {
  const ctx = document.getElementById('topicTrendChart');
  if (!ctx) return;
  
  // 模拟趋势数据
  const dates = ['7/9', '7/10', '7/11', '7/12', '7/13', '7/14', '7/15'];
  const data = [12, 19, 15, 22, 18, 25, 30];
  
  new Chart(ctx, {
    type: 'line',
    data: {
      labels: dates,
      datasets: [{
        label: '新增情报数量',
        data: data,
        backgroundColor: 'rgba(59, 130, 246, 0.1)',
        borderColor: 'rgba(59, 130, 246, 1)',
        borderWidth: 2,
        tension: 0.3,
        fill: true
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          grid: {
            color: 'rgba(0, 0, 0, 0.05)'
          }
        },
        x: {
          grid: {
            display: false
          }
        }
      }
    }
  });
}

// 显示AI分析结果
function showAIAnalysis(topic) {
  const contentArea = document.getElementById('content-area');
  if (!contentArea) return;
  
  contentArea.innerHTML = `
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-4">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-bold text-gray-800">AI解读 - ${topic.name}</h2>
        <button id="backToTopicsFromAI" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg">
          返回专题列表
        </button>
      </div>
      
      <div class="mb-8">
        <div class="flex items-center mb-4">
          <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center mr-3">
            <i class="fa fa-robot text-blue-600 text-xl"></i>
          </div>
          <div>
            <p class="text-gray-800 font-medium">威胁情报AI助手</p>
            <p class="text-gray-500 text-sm">解读生成时间: 刚刚</p>
          </div>
        </div>
        
        <div class="bg-blue-50 border border-blue-100 rounded-xl p-5">
          <h3 class="text-lg font-semibold text-gray-800 mb-3">解读摘要</h3>
          <p class="text-gray-700 mb-4">${topic.aiInsights.summary}</p>
          
          <h3 class="text-lg font-semibold text-gray-800 mb-3">关键发现</h3>
          <ul class="list-disc list-inside space-y-2 mb-4 text-gray-700">
            ${topic.aiInsights.keyFindings.map(finding => `
              <li>${finding}</li>
            `).join('')}
          </ul>
          
          <h3 class="text-lg font-semibold text-gray-800 mb-3">安全建议</h3>
          <ul class="list-disc list-inside space-y-2 text-gray-700">
            ${topic.aiInsights.recommendations.map(rec => `
              <li>${rec}</li>
            `).join('')}
          </ul>
        </div>
      </div>
      
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div class="border border-gray-200 rounded-xl p-4">
          <h3 class="font-semibold text-gray-800 mb-3">相关证据</h3>
          <div class="space-y-3">
            <div class="p-3 bg-gray-50 rounded-lg">
              <p class="text-sm font-medium text-gray-800">APT活动样本</p>
              <p class="text-xs text-gray-600 mt-1">最近7天内发现的23个相关样本</p>
            </div>
            <div class="p-3 bg-gray-50 rounded-lg">
              <p class="text-sm font-medium text-gray-800">IOC指标</p>
              <p class="text-xs text-gray-600 mt-1">128个IP地址，35个域名，42个哈希值</p>
            </div>
          </div>
        </div>
        
        <div class="border border-gray-200 rounded-xl p-4">
          <h3 class="font-semibold text-gray-800 mb-3">关联情报</h3>
          <div class="space-y-3">
            <div class="p-3 bg-gray-50 rounded-lg">
              <p class="text-sm font-medium text-gray-800">历史解读版本</p>
              <p class="text-xs text-gray-600 mt-1">查看过去7次的解读结果对比</p>
            </div>
            <div class="p-3 bg-gray-50 rounded-lg">
              <p class="text-sm font-medium text-gray-800">相关专题</p>
              <p class="text-xs text-gray-600 mt-1">3个关联专题可交叉分析</p>
            </div>
          </div>
        </div>
        
        <div class="border border-gray-200 rounded-xl p-4">
          <h3 class="font-semibold text-gray-800 mb-3">操作选项</h3>
          <div class="space-y-2">
            <button class="w-full btn btn-primary">导出解读报告</button>
            <button class="w-full btn btn-secondary">分享给团队</button>
            <button class="w-full text-sm text-blue-500 hover:text-blue-600">重新生成解读</button>
          </div>
        </div>
      </div>
    </div>
  `;
  
  // 绑定返回按钮事件
  document.getElementById('backToTopicsFromAI').addEventListener('click', function() {
    renderTopicsView();
  });
}

// 渲染AI解读视图
function renderAIInsightsView() {
  const contentArea = document.getElementById('content-area');
  if (!contentArea) return;
  
  const topics = dataManager.getTopics();
  
  contentArea.innerHTML = `
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-4">
      <h2 class="text-xl font-bold text-gray-800 mb-6">AI解读中心</h2>
      
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
        <!-- 最近解读列表 -->
        <div>
          <h3 class="font-semibold text-gray-800 mb-3">最近解读</h3>
          <div class="space-y-3">
            ${topics.slice(0, 3).map(topic => `
              <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                <div class="flex justify-between items-start mb-2">
                  <h4 class="font-medium text-gray-800">${topic.name}</h4>
                  <span class="text-xs text-gray-500">${formatTime(topic.lastUpdated)}</span>
                </div>
                <p class="text-sm text-gray-600 line-clamp-2 mb-3">${topic.aiInsights.summary}</p>
                <div class="flex justify-between items-center">
                  <div class="flex space-x-2">
                    <span class="text-xs bg-blue-100 text-blue-600 px-2 py-0.5 rounded-full">已分析</span>
                    <span class="text-xs bg-green-100 text-green-600 px-2 py-0.5 rounded-full">有建议</span>
                  </div>
                  <button class="text-blue-500 hover:text-blue-600 text-sm" data-topic-id="${topic.id}">
                    查看详情
                  </button>
                </div>
              </div>
            `).join('')}
          </div>
        </div>
        
        <!-- AI解读生成器 -->
        <div>
          <h3 class="font-semibold text-gray-800 mb-3">生成新解读</h3>
          <div class="border border-gray-200 rounded-lg p-4">
            <div class="mb-4">
              <label class="block text-sm text-gray-600 mb-1">选择专题</label>
              <select class="w-full input">
                ${topics.map(topic => `
                  <option value="${topic.id}">${topic.name}</option>
                `).join('')}
              </select>
            </div>
            <div class="mb-4">
              <label class="block text-sm text-gray-600 mb-1">解读类型</label>
              <div class="grid grid-cols-2 gap-2">
                <label class="flex items-center p-2 border border-gray-200 rounded-lg cursor-pointer">
                  <input type="radio" name="analysisType" value="summary" checked class="mr-2">
                  <span class="text-sm">简要分析</span>
                </label>
                <label class="flex items-center p-2 border border-gray-200 rounded-lg cursor-pointer">
                  <input type="radio" name="analysisType" value="detailed" class="mr-2">
                  <span class="text-sm">深度解读</span>
                </label>
                <label class="flex items-center p-2 border border-gray-200 rounded-lg cursor-pointer">
                  <input type="radio" name="analysisType" value="trend" class="mr-2">
                  <span class="text-sm">趋势分析</span>
                </label>
                <label class="flex items-center p-2 border border-gray-200 rounded-lg cursor-pointer">
                  <input type="radio" name="analysisType" value="countermeasure" class="mr-2">
                  <span class="text-sm">防御建议</span>
                </label>
              </div>
            </div>
            <div class="mb-4">
              <label class="block text-sm text-gray-600 mb-1">自定义问题（可选）</label>
              <textarea class="w-full input" rows="3" placeholder="输入你想了解的具体问题..."></textarea>
            </div>
            <button class="w-full btn btn-primary">
              <i class="fa fa-magic mr-2"></i>生成AI解读
            </button>
          </div>
        </div>
      </div>
      
      <div>
        <h3 class="font-semibold text-gray-800 mb-3">解读质量统计</h3>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
          <div class="bg-blue-50 p-4 rounded-lg">
            <p class="text-gray-600 text-sm">总解读次数</p>
            <p class="text-2xl font-bold text-blue-600">24</p>
          </div>
          <div class="bg-green-50 p-4 rounded-lg">
            <p class="text-gray-600 text-sm">高价值解读</p>
            <p class="text-2xl font-bold text-green-600">18</p>
          </div>
          <div class="bg-yellow-50 p-4 rounded-lg">
            <p class="text-gray-600 text-sm">平均生成时间</p>
            <p class="text-2xl font-bold text-yellow-600">12秒</p>
          </div>
          <div class="bg-purple-50 p-4 rounded-lg">
            <p class="text-gray-600 text-sm">采纳率</p>
            <p class="text-2xl font-bold text-purple-600">85%</p>
          </div>
        </div>
        <div class="h-64">
          <canvas id="aiInsightChart"></canvas>
        </div>
      </div>
    </div>
  `;
  
  // 初始化AI洞察图表
  initAIInsightChart();
  
  // 绑定查看详情按钮事件
  const detailButtons = document.querySelectorAll('[data-topic-id]');
  detailButtons.forEach(button => {
    button.addEventListener('click', function() {
      const topicId = this.getAttribute('data-topic-id');
      const topic = dataManager.getTopic(topicId);
      if (topic) {
        showAIAnalysis(topic);
      }
    });
  });
}

// 初始化AI洞察图表
function initAIInsightChart() {
  const ctx = document.getElementById('aiInsightChart');
  if (!ctx) return;
  
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['APT分析', '勒索软件', '供应链攻击', 'DDoS', '零日漏洞'],
      datasets: [{
        label: '解读次数',
        data: [12, 8, 6, 4, 9],
        backgroundColor: [
          'rgba(59, 130, 246, 0.7)',
          'rgba(16, 185, 129, 0.7)',
          'rgba(245, 158, 11, 0.7)',
          'rgba(239, 68, 68, 0.7)',
          'rgba(139, 92, 246, 0.7)'
        ],
        borderRadius: 6
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          grid: {
            color: 'rgba(0, 0, 0, 0.05)'
          }
        },
        x: {
          grid: {
            display: false
          }
        }
      }
    }
  });
}

// 渲染报告导出视图
function renderReportsView() {
  const contentArea = document.getElementById('content-area');
  if (!contentArea) return;
  
  contentArea.innerHTML = `
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-4">
      <h2 class="text-xl font-bold text-gray-800 mb-6">报告导出中心</h2>
      
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
        <!-- 报告类型选择 -->
        <div class="border border-gray-200 rounded-xl p-4">
          <h3 class="font-semibold text-gray-800 mb-3">报告类型</h3>
          <div class="space-y-3">
            <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50">
              <input type="radio" name="reportType" value="intelligence" checked class="mr-3">
              <div>
                <p class="font-medium text-gray-800">情报源质量报告</p>
                <p class="text-xs text-gray-600">所有情报源的质量评估报告</p>
              </div>
            </label>
            <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50">
              <input type="radio" name="reportType" value="topic" class="mr-3">
              <div>
                <p class="font-medium text-gray-800">专题分析报告</p>
                <p class="text-xs text-gray-600">特定专题的深度分析报告</p>
              </div>
            </label>
            <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50">
              <input type="radio" name="reportType" value="ai" class="mr-3">
              <div>
                <p class="font-medium text-gray-800">AI解读报告</p>
                <p class="text-xs text-gray-600">AI生成的威胁解读报告</p>
              </div>
            </label>
            <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50">
              <input type="radio" name="reportType" value="custom" class="mr-3">
              <div>
                <p class="font-medium text-gray-800">自定义报告</p>
                <p class="text-xs text-gray-600">根据需求自定义报告内容</p>
              </div>
            </label>
          </div>
        </div>
        
        <!-- 导出选项 -->
        <div class="border border-gray-200 rounded-xl p-4">
          <h3 class="font-semibold text-gray-800 mb-3">导出选项</h3>
          <div class="space-y-4">
            <div>
              <label class="block text-sm text-gray-600 mb-1">时间范围</label>
              <select class="w-full input">
                <option>最近7天</option>
                <option>最近30天</option>
                <option>最近90天</option>
                <option>自定义...</option>
              </select>
            </div>
            <div>
              <label class="block text-sm text-gray-600 mb-1">导出格式</label>
              <div class="grid grid-cols-3 gap-2">
                <label class="flex items-center justify-center p-2 border border-gray-200 rounded-lg cursor-pointer">
                  <input type="radio" name="exportFormat" value="pdf" checked class="mr-2">
                  <span class="text-sm">PDF</span>
                </label>
                <label class="flex items-center justify-center p-2 border border-gray-200 rounded-lg cursor-pointer">
                  <input type="radio" name="exportFormat" value="excel" class="mr-2">
                  <span class="text-sm">Excel</span>
                </label>
                <label class="flex items-center justify-center p-2 border border-gray-200 rounded-lg cursor-pointer">
                  <input type="radio" name="exportFormat" value="csv" class="mr-2">
                  <span class="text-sm">CSV</span>
                </label>
              </div>
            </div>
            <div>
              <label class="block text-sm text-gray-600 mb-1">报告语言</label>
              <select class="w-full input">
                <option>简体中文</option>
                <option>English</option>
              </select>
            </div>
            <div class="flex items-center">
              <input type="checkbox" id="includeCharts" class="mr-2">
              <label for="includeCharts" class="text-sm text-gray-700">包含图表</label>
            </div>
            <div class="flex items-center">
              <input type="checkbox" id="includeRawData" class="mr-2">
              <label for="includeRawData" class="text-sm text-gray-700">包含原始数据</label>
            </div>
          </div>
        </div>
        
        <!-- 导出操作 -->
        <div class="border border-gray-200 rounded-xl p-4">
          <h3 class="font-semibold text-gray-800 mb-3">导出操作</h3>
          <div class="space-y-4">
            <div class="p-4 bg-blue-50 rounded-lg text-center">
              <i class="fa fa-file-text-o text-blue-600 text-3xl mb-2"></i>
              <p class="text-sm text-gray-700">准备生成报告</p>
              <p class="text-xs text-gray-500 mt-1">点击导出按钮开始生成</p>
            </div>
            <button class="w-full btn btn-primary">
              <i class="fa fa-download mr-2"></i>立即导出
            </button>
            <button class="w-full btn btn-secondary">
              <i class="fa fa-schedule mr-2"></i>定时导出
            </button>
            <div class="text-sm text-gray-600">
              <p>最近导出记录：</p>
              <div class="mt-2 space-y-1">
                <div class="flex justify-between items-center text-xs">
                  <span>情报源质量报告_2024-07-10.pdf</span>
                  <a href="#" class="text-blue-500">下载</a>
                </div>
                <div class="flex justify-between items-center text-xs">
                  <span>专题分析报告_2024-07-08.pdf</span>
                  <a href="#" class="text-blue-500">下载</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div>
        <h3 class="font-semibold text-gray-800 mb-3">报告模板管理</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
            <div class="flex justify-between items-start mb-2">
              <h4 class="font-medium text-gray-800">标准质量报告</h4>
              <span class="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">系统模板</span>
            </div>
            <p class="text-sm text-gray-600 mb-3">包含所有情报源的完整质量评估指标</p>
            <div class="flex justify-end">
              <button class="text-blue-500 hover:text-blue-600 text-sm">使用</button>
            </div>
          </div>
          <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
            <div class="flex justify-between items-start mb-2">
              <h4 class="font-medium text-gray-800">专题摘要报告</h4>
              <span class="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">系统模板</span>
            </div>
            <p class="text-sm text-gray-600 mb-3">专题情报的核心发现和趋势摘要</p>
            <div class="flex justify-end">
              <button class="text-blue-500 hover:text-blue-600 text-sm">使用</button>
            </div>
          </div>
          <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
            <div class="flex justify-between items-start mb-2">
              <h4 class="font-medium text-gray-800">自定义月度报告</h4>
              <span class="text-xs bg-green-100 text-green-600 px-2 py-0.5 rounded-full">我的模板</span>
            </div>
            <p class="text-sm text-gray-600 mb-3">每月威胁情报分析汇总报告</p>
            <div class="flex justify-end space-x-2">
              <button class="text-blue-500 hover:text-blue-600 text-sm">使用</button>
              <button class="text-gray-500 hover:text-gray-600 text-sm">编辑</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  `;
}

// 初始化交互功能
function initInteractions() {
  // 初始化搜索功能
  initSearchFunctionality();
  
  // 初始化筛选功能
  initFilterFunctionality();
  
  // 初始化拖拽排序
  initDragAndDrop();
  
  // 初始化通知功能
  initNotifications();
}

// 初始化搜索功能
function initSearchFunctionality() {
  const searchInput = document.getElementById('global-search');
  if (searchInput) {
    searchInput.addEventListener('input', function() {
      const searchTerm = this.value.toLowerCase().trim();
      if (searchTerm.length > 0) {
        // 模拟搜索效果
        console.log('搜索:', searchTerm);
      }
    });
  }
}

// 初始化筛选功能
function initFilterFunctionality() {
  const filterButtons = document.querySelectorAll('.filter-btn');
  const searchInput = document.getElementById('search-input');
  
  // 筛选按钮点击事件
  filterButtons.forEach(button => {
    button.addEventListener('click', function() {
      this.classList.toggle('bg-blue-50');
      this.classList.toggle('text-blue-600');
      
      // 筛选条件变化时更新视图
      applyFilters();
    });
  });
  
  // 搜索框输入事件
  if (searchInput) {
    searchInput.addEventListener('input', debounce(applyFilters, 300));
  }
  
  // 排序选择器事件
  const sortSelect = document.getElementById('sort-select');
  if (sortSelect) {
    sortSelect.addEventListener('change', applyFilters);
  }
}

// 应用筛选条件并更新视图
function applyFilters() {
  // 获取选中的筛选条件
  const selectedFilters = getSelectedFilters();
  
  // 根据筛选条件过滤情报源
  const filteredSources = filterSources(selectedFilters);
  
  // 更新情报源列表显示
  updateSourcesDisplay(filteredSources);
  
  // 更新图表显示
  updateChartsWithFilters(filteredSources);
  
  // 更新统计信息
  updateStatistics(filteredSources);
}

// 获取选中的筛选条件
function getSelectedFilters() {
  const filters = {
    status: [],
    type: [],
    searchQuery: '',
    sortBy: 'default'
  };
  
  // 获取状态筛选
  document.querySelectorAll('.filter-btn[data-category="status"].bg-blue-50').forEach(btn => {
    filters.status.push(btn.dataset.filter);
  });
  
  // 获取类型筛选
  document.querySelectorAll('.filter-btn[data-category="type"].bg-blue-50').forEach(btn => {
    filters.type.push(btn.dataset.filter);
  });
  
  // 获取搜索关键词
  const searchInput = document.getElementById('search-input');
  if (searchInput) {
    filters.searchQuery = searchInput.value.toLowerCase();
  }
  
  // 获取排序方式
  const sortSelect = document.getElementById('sort-select');
  if (sortSelect) {
    filters.sortBy = sortSelect.value;
  }
  
  return filters;
}

// 根据筛选条件过滤情报源
function filterSources(filters) {
  const sources = dataManager.getIntelligenceSources();
  
  return sources.filter(source => {
    // 状态筛选
    if (filters.status.length > 0 && !filters.status.includes(source.status)) {
      return false;
    }
    
    // 类型筛选
    if (filters.type.length > 0 && !filters.type.includes(source.type)) {
      return false;
    }
    
    // 搜索筛选
    if (filters.searchQuery && 
        !source.name.toLowerCase().includes(filters.searchQuery) &&
        !source.type.toLowerCase().includes(filters.searchQuery)) {
      return false;
    }
    
    return true;
  }).sort((a, b) => {
    // 排序逻辑
    switch (filters.sortBy) {
      case 'quality-desc':
        return b.qualityScore - a.qualityScore;
      case 'quality-asc':
        return a.qualityScore - b.qualityScore;
      case 'update-desc':
        return new Date(b.lastUpdated) - new Date(a.lastUpdated);
      case 'update-asc':
        return new Date(a.lastUpdated) - new Date(b.lastUpdated);
      case 'name-asc':
        return a.name.localeCompare(b.name);
      case 'name-desc':
        return b.name.localeCompare(a.name);
      default:
        return 0;
    }
  });
}

// 更新情报源显示
function updateSourcesDisplay(filteredSources) {
  const sourcesContainer = document.getElementById('intelligence-sources');
  if (!sourcesContainer) return;
  
  // 确保保持网格布局样式
  sourcesContainer.className = 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4';
  
  sourcesContainer.innerHTML = '';
  
  if (filteredSources.length === 0) {
    sourcesContainer.innerHTML = `
      <div class="text-center py-12 w-full">
        <div class="text-gray-400 mb-4">
          <i class="fa fa-search text-4xl"></i>
        </div>
        <h3 class="text-lg font-medium text-gray-700">未找到匹配的情报源</h3>
        <p class="text-gray-500 mt-2">请尝试调整筛选条件</p>
      </div>
    `;
    return;
  }
  
  filteredSources.forEach(source => {
    const card = createSourceCard(source);
    sourcesContainer.appendChild(card);
  });
}

// 更新图表显示
function updateChartsWithFilters(filteredSources) {
  // 更新质量分布图表
  if (window.qualityChart) {
    updateQualityChart(filteredSources);
  }
  
  // 如果在专题视图，更新相关图表
  if (document.querySelector('.topics-view')) {
    // 这里可以添加专题视图的图表更新逻辑
  }
}

// 更新质量分布图表
function updateQualityChart(filteredSources) {
  // 统计各状态的情报源数量
  const statusCount = {
    excellent: 0,
    good: 0,
    normal: 0,
    warning: 0
  };
  
  filteredSources.forEach(source => {
    statusCount[source.status] = (statusCount[source.status] || 0) + 1;
  });
  
  // 更新图表数据
  window.qualityChart.data.labels = ['优秀', '良好', '一般', '需关注'];
  window.qualityChart.data.datasets[0].data = [
    statusCount.excellent,
    statusCount.good,
    statusCount.normal,
    statusCount.warning
  ];
  
  window.qualityChart.update();
}

// 更新统计信息
function updateStatistics(filteredSources) {
  const totalCountElement = document.getElementById('total-sources-count');
  const avgQualityElement = document.getElementById('avg-quality-score');
  
  if (totalCountElement) {
    totalCountElement.textContent = filteredSources.length;
  }
  
  if (avgQualityElement && filteredSources.length > 0) {
    const avgScore = filteredSources.reduce((sum, source) => sum + source.qualityScore, 0) / filteredSources.length;
    avgQualityElement.textContent = avgScore.toFixed(1);
  }
}

// 防抖函数
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// 初始化拖拽排序
function initDragAndDrop() {
  console.log('初始化拖拽排序功能');
  
  // 为每个情报源卡片添加拖拽功能
  const sourceCards = document.querySelectorAll('.intelligence-source-card');
  sourceCards.forEach(card => {
    // 设置为可拖拽
    card.draggable = true;
    
    // 添加拖拽开始事件
    card.addEventListener('dragstart', handleDragStart);
    
    // 添加拖拽结束事件
    card.addEventListener('dragend', handleDragEnd);
    
    // 添加拖拽经过事件
    card.addEventListener('dragover', handleDragOver);
    
    // 添加拖拽进入事件
    card.addEventListener('dragenter', handleDragEnter);
    
    // 添加拖拽离开事件
    card.addEventListener('dragleave', handleDragLeave);
    
    // 添加放置事件
    card.addEventListener('drop', handleDrop);
  });
}

// 拖拽开始处理函数
function handleDragStart(e) {
  // 保存被拖拽元素的数据
  this.classList.add('dragging');
  e.dataTransfer.setData('text/plain', this.id);
  e.dataTransfer.effectAllowed = 'move';
  
  // 添加拖拽视觉效果
  setTimeout(() => {
    this.classList.add('opacity-50');
  }, 0);
}

// 拖拽结束处理函数
function handleDragEnd() {
  // 移除拖拽状态样式
  this.classList.remove('dragging', 'opacity-50');
  
  // 移除所有放置目标样式
  document.querySelectorAll('.drop-target').forEach(el => {
    el.classList.remove('drop-target');
  });
}

// 拖拽经过处理函数
function handleDragOver(e) {
  // 阻止默认行为以允许放置
  e.preventDefault();
  e.dataTransfer.dropEffect = 'move';
}

// 拖拽进入处理函数
function handleDragEnter(e) {
  // 阻止默认行为
  e.preventDefault();
  
  // 如果不是正在拖拽的元素本身，则添加放置目标样式
  if (!this.classList.contains('dragging')) {
    this.classList.add('drop-target');
  }
}

// 拖拽离开处理函数
function handleDragLeave() {
  // 移除放置目标样式
  this.classList.remove('drop-target');
}

// 放置处理函数
function handleDrop(e) {
  // 阻止默认行为
  e.preventDefault();
  
  // 获取被拖拽元素的ID
  const draggedId = e.dataTransfer.getData('text/plain');
  const draggedElement = document.getElementById(draggedId);
  
  // 移除放置目标样式
  this.classList.remove('drop-target');
  
  // 如果是有效拖拽（不是拖拽到自身）
  if (draggedElement && draggedElement !== this) {
    const container = this.parentNode;
    
    // 计算位置并插入元素
    const afterElement = getDragAfterElement(container, e.clientY);
    
    if (afterElement == null) {
      container.appendChild(draggedElement);
    } else {
      container.insertBefore(draggedElement, afterElement);
    }
    
    // 更新本地存储中的排序
    updateSourcesOrder(container);
    
    // 添加放置成功的视觉反馈
    draggedElement.classList.add('transition-all', 'scale-105');
    setTimeout(() => {
      draggedElement.classList.remove('scale-105');
    }, 300);
  }
}

// 计算拖拽位置后的元素
function getDragAfterElement(container, y) {
  const draggableElements = [...container.querySelectorAll('.intelligence-source-card:not(.dragging)')];
  
  return draggableElements.reduce((closest, child) => {
    const box = child.getBoundingClientRect();
    const offset = y - box.top - box.height / 2;
    
    if (offset < 0 && offset > closest.offset) {
      return { offset: offset, element: child };
    } else {
      return closest;
    }
  }, { offset: Number.NEGATIVE_INFINITY }).element;
}

// 更新情报源排序
function updateSourcesOrder(container) {
  const cards = container.querySelectorAll('.intelligence-source-card');
  const sourceIds = Array.from(cards).map(card => card.id.replace('source-', ''));
  
  // 获取现有数据
  const sources = dataManager.getIntelligenceSources();
  
  // 重新排序数据
  const reorderedSources = [];
  sourceIds.forEach(id => {
    const source = sources.find(s => s.id === id);
    if (source) reorderedSources.push(source);
  });
  
  // 保存到本地存储
  dataManager.saveIntelligenceSources(reorderedSources);
  
  console.log('情报源排序已更新');
}

// 初始化通知功能
function initNotifications() {
  const notificationBtn = document.getElementById('notification-btn');
  if (notificationBtn) {
    notificationBtn.addEventListener('click', function() {
      // 模拟通知点击效果
      const badge = this.querySelector('.notification-badge');
      if (badge) {
        badge.remove();
      }
    });
  }
}

// 初始化用户体验增强功能
function initUXEnhancements() {
  // 启用平滑滚动
  enableSmoothScroll();
  
  // 增强模态框交互
  enhanceModalInteractions();
  
  // 添加键盘导航支持
  addKeyboardNavigation();
  
  // 添加加载状态管理
  initLoadingState();
}

// 启用平滑滚动
function enableSmoothScroll() {
  // 为所有锚点链接添加平滑滚动
  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
      e.preventDefault();
      const targetId = this.getAttribute('href');
      
      // 避免无效的选择器错误
      if (targetId === '#') {
        // 如果只是#，滚动到页面顶部
        window.scrollTo({ 
          top: 0,
          behavior: 'smooth'
        });
      } else {
        // 正常处理其他锚点
        const targetElement = document.querySelector(targetId);
        if (targetElement) {
          targetElement.scrollIntoView({ 
            behavior: 'smooth',
            block: 'start'
          });
        }
      }
    });
  });
  
  // 启用页面级平滑滚动
  document.documentElement.style.scrollBehavior = 'smooth';
}

// 增强模态框交互
function enhanceModalInteractions() {
  // 为所有模态框添加ESC关闭功能
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
      closeModals();
    }
  });
  
  // 为模态框背景添加点击关闭功能
  document.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal-overlay')) {
      closeModals();
    }
  });
  
  // 自动聚焦第一个输入字段
  const modals = document.querySelectorAll('.modal-content');
  modals.forEach(modal => {
    modal.addEventListener('DOMNodeInserted', function() {
      const firstInput = this.querySelector('input, select, textarea');
      if (firstInput) {
        setTimeout(() => firstInput.focus(), 100);
      }
    });
  });
}

// 关闭所有模态框
function closeModals() {
  const modals = document.querySelectorAll('.modal-overlay');
  modals.forEach(modal => {
    modal.classList.add('hidden');
  });
  
  // 恢复背景滚动
  document.body.style.overflow = '';
  
  // 移除模态框相关的事件监听器
  document.querySelectorAll('.modal-close').forEach(btn => {
    btn.removeEventListener('click', closeModals);
  });
  
  // 为关闭按钮重新添加事件监听器
  document.querySelectorAll('.modal-close').forEach(btn => {
    btn.addEventListener('click', closeModals);
  });
}

// 添加键盘导航支持
function addKeyboardNavigation() {
  // 为卡片列表添加键盘导航
  const sourceContainer = document.getElementById('intelligence-sources-container');
  if (sourceContainer) {
    let focusedIndex = -1;
    const cards = sourceContainer.querySelectorAll('.source-card');
    
    // 处理键盘导航
    document.addEventListener('keydown', function(e) {
      // 仅在没有输入框聚焦时处理导航键
      if (!['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement.tagName)) {
        switch(e.key) {
          case 'ArrowRight':
            e.preventDefault();
            if (focusedIndex < cards.length - 1) {
              focusedIndex++;
              cards[focusedIndex].focus();
            }
            break;
          case 'ArrowLeft':
            e.preventDefault();
            if (focusedIndex > 0) {
              focusedIndex--;
              cards[focusedIndex].focus();
            }
            break;
          case 'Enter':
            if (focusedIndex >= 0 && focusedIndex < cards.length) {
              e.preventDefault();
              const clickEvent = new MouseEvent('click', { bubbles: true });
              cards[focusedIndex].dispatchEvent(clickEvent);
            }
            break;
        }
      }
    });
    
    // 初始化卡片可聚焦
    cards.forEach((card, index) => {
      card.setAttribute('tabindex', '0');
      card.addEventListener('focus', () => {
        focusedIndex = index;
        card.classList.add('focused');
      });
      card.addEventListener('blur', () => {
        card.classList.remove('focused');
      });
    });
  }
}

// 添加加载状态管理
function initLoadingState() {
  // 创建全局加载指示器
  const loadingIndicator = document.createElement('div');
  loadingIndicator.id = 'global-loading';
  loadingIndicator.className = 'fixed inset-0 flex items-center justify-center bg-black bg-opacity-30 z-50 hidden';
  loadingIndicator.innerHTML = `
    <div class="bg-white p-6 rounded-lg shadow-lg flex items-center gap-3">
      <div class="loading"></div>
      <span>正在加载...</span>
    </div>
  `;
  document.body.appendChild(loadingIndicator);
  
  // 暴露全局加载控制函数
  window.showLoading = function(message = '正在加载...') {
    const indicator = document.getElementById('global-loading');
    if (indicator) {
      indicator.querySelector('span').textContent = message;
      indicator.classList.remove('hidden');
    }
  };
  
  window.hideLoading = function() {
    const indicator = document.getElementById('global-loading');
    if (indicator) {
      indicator.classList.add('hidden');
    }
  };
}

// 显示通知消息
function showNotification(message, type = 'info') {
  // 创建通知元素
  const notification = document.createElement('div');
  notification.className = `fixed bottom-4 right-4 p-4 rounded-lg shadow-lg transition-all duration-300 transform translate-y-0 opacity-0 z-50 flex items-center gap-3`;
  
  // 设置不同类型的样式
  switch(type) {
    case 'success':
      notification.classList.add('bg-emerald-50', 'border-l-4', 'border-emerald-500', 'text-emerald-800');
      notification.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
          <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
        </svg>
        <span>${message}</span>
      `;
      break;
    case 'error':
      notification.classList.add('bg-red-50', 'border-l-4', 'border-red-500', 'text-red-800');
      notification.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
          <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
        </svg>
        <span>${message}</span>
      `;
      break;
    case 'warning':
      notification.classList.add('bg-amber-50', 'border-l-4', 'border-amber-500', 'text-amber-800');
      notification.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
          <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
        </svg>
        <span>${message}</span>
      `;
      break;
    default: // info
      notification.classList.add('bg-blue-50', 'border-l-4', 'border-blue-500', 'text-blue-800');
      notification.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
          <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
        </svg>
        <span>${message}</span>
      `;
  }
  
  // 添加到文档
  document.body.appendChild(notification);
  
  // 淡入动画
  setTimeout(() => {
    notification.classList.remove('opacity-0');
    notification.classList.add('opacity-100');
  }, 10);
  
  // 自动消失
  setTimeout(() => {
    notification.classList.add('opacity-0', 'translate-y-4');
    setTimeout(() => {
      notification.remove();
    }, 300);
  }, 3000);
}

// 显示编辑情报源模态框
function showEditSourceModal(source) {
  // 获取模态框元素
  const modal = document.getElementById('edit-source-modal');
  if (!modal) return;
  
  // 填充表单数据
  document.getElementById('edit-source-id').value = source.id;
  document.getElementById('edit-source-name').value = source.name;
  document.getElementById('edit-source-type').value = source.type;
  document.getElementById('edit-source-frequency').value = source.updateFrequency || '每日';
  document.getElementById('edit-source-coverage').value = source.coverage || '';
  document.getElementById('edit-source-reliability').value = source.reliability || '中';
  
  // 显示模态框
  modal.classList.remove('hidden');
  
  console.log('编辑情报源:', source.name);
}

// 关闭编辑模态框
function closeEditSourceModal() {
  const modal = document.getElementById('edit-source-modal');
  if (modal) {
    modal.classList.add('hidden');
  }
}

// 初始化编辑模态框事件
function initEditModalEvents() {
  // 绑定关闭按钮事件
  const closeBtn = document.getElementById('close-edit-modal');
  if (closeBtn) {
    closeBtn.addEventListener('click', closeEditSourceModal);
  }
  
  // 绑定取消按钮事件
  const cancelBtn = document.getElementById('cancel-edit-source');
  if (cancelBtn) {
    cancelBtn.addEventListener('click', closeEditSourceModal);
  }
  
  // 绑定表单提交事件
  const form = document.getElementById('edit-source-form');
  if (form) {
    form.addEventListener('submit', function(e) {
      e.preventDefault();
      
      // 获取表单数据
      const sourceId = document.getElementById('edit-source-id').value;
      const updatedData = {
        name: document.getElementById('edit-source-name').value,
        type: document.getElementById('edit-source-type').value,
        updateFrequency: document.getElementById('edit-source-frequency').value,
        coverage: document.getElementById('edit-source-coverage').value,
        reliability: document.getElementById('edit-source-reliability').value
      };
      
      // 调用更新函数
      updateIntelligenceSource(sourceId, updatedData);
      
      // 关闭模态框
      closeEditSourceModal();
    });
  }
}

// 显示评估模态框
function showEvaluationModal(source) {
  // 这里应该打开评估详情模态框
  console.log('评估情报源:', source.name);
  
  // 模拟模态框提示
  alert('评估功能：' + source.name);
}

// 格式化时间
function formatTime(timestamp) {
  const date = new Date(timestamp);
  const now = new Date();
  const diffInMs = now - date;
  const diffInMinutes = Math.floor(diffInMs / (1000 * 60));
  const diffInHours = Math.floor(diffInMinutes / 60);
  const diffInDays = Math.floor(diffInHours / 24);
  
  if (diffInMinutes < 1) {
    return '刚刚';
  } else if (diffInMinutes < 60) {
    return `${diffInMinutes}分钟前`;
  } else if (diffInHours < 24) {
    return `${diffInHours}小时前`;
  } else if (diffInDays < 30) {
    return `${diffInDays}天前`;
  } else {
    return date.toLocaleDateString('zh-CN');
  }
}

// 获取状态样式
function getStatusStyles(status) {
  switch (status) {
    case 'excellent':
      return { color: 'text-green-600', label: '优秀' };
    case 'good':
      return { color: 'text-blue-600', label: '良好' };
    case 'normal':
      return { color: 'text-yellow-600', label: '一般' };
    case 'warning':
      return { color: 'text-red-600', label: '需关注' };
    default:
      return { color: 'text-gray-600', label: '未知' };
  }
}

// 专题管理相关函数

// 显示添加专题模态框
function showAddTopicModal() {
  const modal = document.getElementById('add-topic-modal');
  if (modal) {
    modal.classList.remove('hidden');
    // 重置表单
    document.getElementById('add-topic-form').reset();
  }
}

// 关闭添加专题模态框
function closeAddTopicModal() {
  const modal = document.getElementById('add-topic-modal');
  if (modal) {
    modal.classList.add('hidden');
  }
}

// 初始化添加专题模态框事件
function initAddTopicModal() {
  // 绑定关闭按钮事件
  const closeBtn = document.getElementById('close-topic-modal');
  if (closeBtn) {
    closeBtn.addEventListener('click', closeAddTopicModal);
  }
  
  // 绑定取消按钮事件
  const cancelBtn = document.getElementById('cancel-add-topic');
  if (cancelBtn) {
    cancelBtn.addEventListener('click', closeAddTopicModal);
  }
  
  // 绑定左侧面板的添加专题按钮事件
  const leftAddTopicBtn = document.querySelector('.text-blue-500 i.fa-plus-circle').parentElement;
  if (leftAddTopicBtn) {
    leftAddTopicBtn.addEventListener('click', showAddTopicModal);
  }
}

// 处理添加专题表单提交
function handleAddTopicSubmit(e) {
  e.preventDefault();
  
  // 获取表单元素
  const nameInput = document.getElementById('topic-name');
  const descriptionInput = document.getElementById('topic-description');
  const statusInput = document.getElementById('topic-status');
  const frequencyInput = document.getElementById('topic-frequency');
  const keywordsInput = document.getElementById('topic-keywords');
  
  // 表单验证
  if (!nameInput.value.trim()) {
    showNotification('专题名称不能为空', 'error');
    nameInput.focus();
    return;
  }
  
  // 收集表单数据
  const formData = {
    name: nameInput.value.trim(),
    description: descriptionInput.value.trim(),
    status: statusInput.value,
    pushFrequency: frequencyInput.value,
    // 处理关键词，转换为数组
    keywords: keywordsInput.value
      .split(',')
      .map(keyword => keyword.trim())
      .filter(keyword => keyword !== '')
  };
  
  // 生成必要的默认数据
  formData.id = `t${Date.now()}`;
  formData.lastUpdated = new Date().toISOString();
  formData.newContentCount = 0;
  formData.sources = [];
  formData.aiInsights = {
    summary: '新建专题暂无AI解读',
    keyFindings: ['专题刚刚创建'],
    recommendations: ['建议关联相关情报源']
  };
  
  // 保存专题
  const result = saveTopic(formData);
  
  if (result.success) {
    // 显示成功消息
    showNotification('专题添加成功', 'success');
    // 关闭模态框
    closeAddTopicModal();
    // 更新左侧专题列表显示
    updateTopicListDisplay();
  } else {
    // 显示错误消息
    showNotification(`添加专题失败: ${result.error}`, 'error');
  }
}

// 处理快速创建专题功能
function handleQuickCreateTopic() {
  // 获取快速创建表单元素
  const quickNameInput = document.getElementById('quick-topic-name');
  const quickKeywordsInput = document.getElementById('quick-topic-keywords');
  const quickFrequencySelect = document.getElementById('quick-topic-frequency');
  
  // 表单验证 - 专题名称必填
  if (!quickNameInput.value.trim()) {
    showNotification('专题名称不能为空', 'error');
    quickNameInput.focus();
    return;
  }
  
  // 收集表单数据
  const formData = {
    name: quickNameInput.value.trim(),
    description: '', // 快速创建时描述为空
    status: 'active', // 默认激活状态
    pushFrequency: quickFrequencySelect.value || 'daily', // 使用选择的推送频率或默认每日
    // 处理关键词，转换为数组
    keywords: quickKeywordsInput.value
      .split(',')
      .map(keyword => keyword.trim())
      .filter(keyword => keyword !== '')
  };
  
  // 生成必要的默认数据
  formData.id = `t${Date.now()}`;
  formData.lastUpdated = new Date().toISOString();
  formData.newContentCount = 0;
  formData.sources = [];
  formData.aiInsights = {
    summary: '新建专题暂无AI解读',
    keyFindings: ['专题刚刚创建'],
    recommendations: ['建议关联相关情报源']
  };
  
  // 保存专题
  const result = saveTopic(formData);
  
  if (result.success) {
    // 显示成功消息
    showNotification('专题快速创建成功', 'success');
    // 清空快速创建表单
    quickNameInput.value = '';
    quickKeywordsInput.value = '';
    quickFrequencySelect.value = 'daily';
    // 更新左侧专题列表显示
    updateTopicListDisplay();
  } else {
    // 显示错误消息
    showNotification(`快速创建专题失败: ${result.error}`, 'error');
  }
}

// 更新左侧专题列表显示
function updateTopicListDisplay() {
  // 获取专题列表容器
  const topicListContainer = document.querySelector('.bg-white.rounded-xl.shadow-sm.border.border-gray-200.p-4.mb-4:nth-of-type(2) .space-y-2');
  
  if (!topicListContainer) return;
  
  // 获取最新的专题数据
  const topics = dataManager.getTopics();
  
  // 清空容器
  topicListContainer.innerHTML = '';
  
  // 重新渲染专题列表
  topics.forEach(topic => {
    const topicElement = document.createElement('div');
    topicElement.className = 'flex items-center justify-between p-2 rounded-lg hover:bg-gray-50';
    
    let statusBadge = '';
    if (topic.newContentCount > 0) {
      statusBadge = `<span class="bg-red-100 text-red-600 text-xs px-2 py-1 rounded-full">${topic.newContentCount}个新</span>`;
    } else {
      switch(topic.status) {
        case 'active':
          statusBadge = '<span class="bg-green-100 text-green-600 text-xs px-2 py-1 rounded-full">活跃</span>';
          break;
        case 'pending':
          statusBadge = '<span class="bg-yellow-100 text-yellow-600 text-xs px-2 py-1 rounded-full">待更新</span>';
          break;
        default:
          statusBadge = '<span class="bg-blue-100 text-blue-600 text-xs px-2 py-1 rounded-full">正常</span>';
      }
    }
    
    topicElement.innerHTML = `
      <span class="text-sm font-medium">${topic.name}</span>
      ${statusBadge}
    `;
    
    topicListContainer.appendChild(topicElement);
  });
}

// 保存专题
function saveTopic(topicData) {
  try {
    // 确保lastUpdated是ISO格式的字符串，与mock数据保持一致
    if (typeof topicData.lastUpdated !== 'string') {
      topicData.lastUpdated = new Date().toISOString();
    }
    
    // 使用dataManager.saveTopic方法保存专题数据
    dataManager.saveTopic(topicData);
    
    // 更新视图
    renderTopicsView();
    
    console.log('专题保存成功:', topicData.name);
    return { success: true };
  } catch (error) {
    console.error('保存专题失败:', error);
    return { success: false, error: error.message };
  }
}

// 更新专题
function updateTopic(topicId, updatedData) {
  try {
    // 获取现有数据
    const topics = dataManager.getTopics();
    
    // 查找并更新
    const index = topics.findIndex(t => t.id === topicId);
    if (index === -1) {
      throw new Error('未找到指定的专题');
    }
    
    // 更新数据
    topics[index] = { ...topics[index], ...updatedData, lastUpdated: Date.now() };
    
    // 保存到本地存储
    dataManager.saveTopics(topics);
    
    // 更新视图
    renderTopicsView();
    
    console.log('专题更新成功:', topicId);
    return { success: true };
  } catch (error) {
    console.error('更新专题失败:', error);
    return { success: false, error: error.message };
  }
}

// 删除专题
function deleteTopic(topicId) {
  try {
    // 获取现有数据
    const topics = dataManager.getTopics();
    
    // 过滤掉要删除的项目
    const updatedTopics = topics.filter(t => t.id !== topicId);
    
    // 保存到本地存储
    dataManager.saveTopics(updatedTopics);
    
    // 更新视图
    renderTopicsView();
    
    console.log('专题删除成功:', topicId);
    return { success: true };
  } catch (error) {
    console.error('删除专题失败:', error);
    return { success: false, error: error.message };
  }
}

// 质量评估模型管理函数

// 保存质量评估模型
function saveQualityModel(modelData) {
  try {
    // 生成唯一ID
    if (!modelData.id) {
      modelData.id = Date.now().toString();
    }
    modelData.lastUpdated = Date.now();
    
    // 获取现有数据
    const models = dataManager.getQualityModels();
    
    // 检查是否已存在
    const index = models.findIndex(m => m.id === modelData.id);
    if (index === -1) {
      // 添加新模型
      models.push(modelData);
    } else {
      // 更新现有模型
      models[index] = modelData;
    }
    
    // 保存到本地存储
    dataManager.saveQualityModels(models);
    
    console.log('质量评估模型保存成功:', modelData.name);
    return { success: true, model: modelData };
  } catch (error) {
    console.error('保存质量评估模型失败:', error);
    return { success: false, error: error.message };
  }
}

// 导出配置为JSON
function exportConfiguration(modelData) {
  try {
    const dataStr = JSON.stringify(modelData, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
    
    const exportFileDefaultName = `quality_model_${modelData.name || 'export'}_${new Date().toISOString().split('T')[0]}.json`;
    
    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
    
    console.log('配置导出成功');
    return { success: true };
  } catch (error) {
    console.error('导出配置失败:', error);
    return { success: false, error: error.message };
  }
}

// 导入配置
function importConfiguration(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    
    reader.onload = function(e) {
      try {
        const modelData = JSON.parse(e.target.result);
        
        // 验证导入的数据结构
        if (!modelData.name || !modelData.factors) {
          throw new Error('导入的配置文件格式不正确');
        }
        
        // 生成新ID以避免覆盖
        modelData.id = Date.now().toString();
        modelData.lastUpdated = Date.now();
        modelData.imported = true;
        
        // 保存导入的模型
        const result = saveQualityModel(modelData);
        
        if (result.success) {
          resolve(result);
        } else {
          reject(result.error);
        }
      } catch (error) {
        reject(error.message);
      }
    };
    
    reader.onerror = function() {
      reject('文件读取失败');
    };
    
    reader.readAsText(file);
  });
}

// 显示导出选项模态框
function showExportOptions() {
  // 创建模态框
  const modal = document.createElement('div');
  modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
  modal.innerHTML = `
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-bold text-gray-800">导出数据</h3>
        <button id="close-export-modal" class="text-gray-500 hover:text-gray-700">
          <i class="fa fa-times text-xl"></i>
        </button>
      </div>
      <div class="mb-4">
        <p class="text-gray-600 mb-3">请选择要导出的数据类型：</p>
        <div class="space-y-2">
          <label class="flex items-center">
            <input type="radio" name="export-type" value="all" checked class="mr-2">
            <span>导出所有数据</span>
          </label>
          <label class="flex items-center">
            <input type="radio" name="export-type" value="intelligenceSources" class="mr-2">
            <span>仅导出情报源</span>
          </label>
          <label class="flex items-center">
            <input type="radio" name="export-type" value="topics" class="mr-2">
            <span>仅导出专题</span>
          </label>
          <label class="flex items-center">
            <input type="radio" name="export-type" value="evaluationModels" class="mr-2">
            <span>仅导出评估模型</span>
          </label>
        </div>
      </div>
      <div class="flex justify-end space-x-3">
        <button id="cancel-export" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
          取消
        </button>
        <button id="confirm-export" class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors">
          确认导出
        </button>
      </div>
    </div>
  `;
  
  document.body.appendChild(modal);
  
  // 绑定事件
  document.getElementById('close-export-modal').addEventListener('click', () => {
    document.body.removeChild(modal);
  });
  
  document.getElementById('cancel-export').addEventListener('click', () => {
    document.body.removeChild(modal);
  });
  
  document.getElementById('confirm-export').addEventListener('click', () => {
    const exportType = document.querySelector('input[name="export-type"]:checked').value;
    document.body.removeChild(modal);
    exportData(exportType);
  });
  
  // 点击模态框背景关闭
  modal.addEventListener('click', (e) => {
    if (e.target === modal) {
      document.body.removeChild(modal);
    }
  });
}

// 导出数据函数
function exportData(dataType) {
  try {
    window.showLoading('正在导出数据...');
    
    // 获取导出的数据
    const jsonData = dataManager.exportData(dataType);
    
    // 创建下载链接
    const blob = new Blob([jsonData], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    
    // 设置文件名
    let fileName = '威胁情报中心数据_';
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    
    if (dataType === 'all') {
      fileName += '全部数据_';
    } else if (dataType === 'intelligenceSources') {
      fileName += '情报源_';
    } else if (dataType === 'topics') {
      fileName += '专题_';
    } else if (dataType === 'evaluationModels') {
      fileName += '评估模型_';
    }
    
    fileName += timestamp + '.json';
    
    a.href = url;
    a.download = fileName;
    
    // 触发下载
    document.body.appendChild(a);
    a.click();
    
    // 清理
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    window.hideLoading();
    showNotification('数据导出成功', 'success');
  } catch (error) {
    console.error('导出数据错误:', error);
    window.hideLoading();
    showNotification('数据导出失败: ' + error.message, 'error');
  }
}